package com.heima.behavior.service.impl;
import java.util.Date;
import java.util.UUID;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.behavior.mapper.ApReadBehaviorMapper;
import com.heima.behavior.service.ApBehaviorEntryService;
import com.heima.behavior.service.ApReadBehaviorService;
import com.heima.common.constants.article.HotArticleConstants;
import com.heima.model.behavior.dtos.ReadBehaviorDto;
import com.heima.model.behavior.pojos.ApBehaviorEntry;
import com.heima.model.behavior.pojos.ApReadBehavior;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.mess.app.UpdateArticleMess;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.threadlocal.AppThreadLocalUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @作者 itcast
 * @创建日期 2021/2/4 10:51
 **/
@Service
@Slf4j
@Transactional
public class ApReadBehaviorServiceImpl extends ServiceImpl<ApReadBehaviorMapper, ApReadBehavior> implements ApReadBehaviorService {
    @Autowired
    ApBehaviorEntryService apBehaviorEntryService;

    @Autowired
    KafkaTemplate<String,String> kafkaTemplate;


    @Override
    public ResponseResult readBehavior(ReadBehaviorDto dto) {
        log.info("readBehavior 调用,参数==>{}",dto);
        // 1. 检查参数
        if(dto == null || dto.getArticleId() == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        // 2. 查询行为实体数据(userId 设备ID)
        ApUser user = AppThreadLocalUtils.getUser();
        Integer userId = (user == null)?null:user.getId();
        ApBehaviorEntry behaviorEntry = apBehaviorEntryService.findByUserIdOrEquipmentId(userId, dto.getEquipmentId());
        if (behaviorEntry == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"行为实体数据不存在");
        }
        // 3. 根据行为实体及文章ID查询阅读行为是否存在
        ApReadBehavior readBehavior = getOne(
                Wrappers.<ApReadBehavior>lambdaQuery()
                        .eq(ApReadBehavior::getEntryId, behaviorEntry.getId())
                        .eq(ApReadBehavior::getArticleId, dto.getArticleId())
        );
        //      不存在   添加阅读行为
        if(readBehavior == null){
            readBehavior = new ApReadBehavior();
            readBehavior.setEntryId(behaviorEntry.getId());
            readBehavior.setArticleId(dto.getArticleId());
            readBehavior.setCount(dto.getCount());
            readBehavior.setReadDuration(dto.getReadDuration());
            readBehavior.setPercentage(dto.getPercentage());
            readBehavior.setLoadDuration(dto.getLoadDuration());
            readBehavior.setCreatedTime(new Date());
            readBehavior.setUpdatedTime(new Date());
            save(readBehavior);
        }else {
            //      修改    修改阅读行为
            readBehavior.setCount((short)(readBehavior.getCount()+1));
            readBehavior.setReadDuration(readBehavior.getReadDuration() == null ?  dto.getReadDuration() :readBehavior.getReadDuration() + dto.getReadDuration() );
            readBehavior.setUpdatedTime(new Date());
            updateById(readBehavior);
        }
        //发送消息
        UpdateArticleMess mess = new UpdateArticleMess();
        mess.setAdd(1);
        mess.setType(UpdateArticleMess.UpdateArticleType.VIEWS);
        mess.setArticleId(dto.getArticleId());
        kafkaTemplate.send(HotArticleConstants.HOT_ARTICLE_SCORE_TOPIC, UUID.randomUUID().toString(), JSON.toJSONString(mess));
        return ResponseResult.okResult();
    }
}
